package productplan

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"strconv"
	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/until"
	"time"

	"oxy_server/res/cmsserver/designplan"

	"oxy_server/res/cmsserver/productproperty"

	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"
)

type (
	Productplan struct {
		ID                      bson.ObjectId             `json:"_id" bson:"_id"`
		DesignPlanID            string                    `json:"designplanid" bson:"designplanid"`                       //大货号
		Number                  string                    `json:"number" bson:"number"`                                   //流水号
		LargeCargoNumber        string                    `json:"largecargonumber" bson:"largecargonumber"`               //大货号
		Brand                   string                    `json:"brand" bson:"brand"`                                     //品牌
		DesignNumber            string                    `json:"designnumber" bson:"designnumber"`                       //设计号
		ModelName               string                    `json:"modelname" bson:"modelname"`                             //款名
		FactoryNumber           string                    `json:"factorynumber" bson:"factorynumber"`                     //工厂款号
		Gender                  string                    `json:"gender" bson:"gender"`                                   //性别
		ProductCategory         string                    `json:"productcategory" bson:"productcategory"`                 //产品大类
		ProductKind             string                    `json:"productkind" bson:"productkind"`                         //品类
		Color                   []string                  `json:"color" bson:"color"`                                     //颜色
		DesignPic               []string                  `json:"designpic" bson:"designpic"`                             //设计稿
		Designer                string                    `json:"designer" bson:"designer"`                               //设计师
		Batch                   string                    `json:"batch" bson:"batch"`                                     //批次
		Provider                string                    `json:"provider" bson:"provider"`                               //供应商
		FactoryCost             string                    `json:"factorycost" bson:"factorycost"`                         //工厂报价
		TargetCost              string                    `json:"targetcost" bson:"targetcost"`                           //目标成本
		FinallyCost             string                    `json:"finallycost" bson:"finallycost"`                         //最终成本 设计组物料单中带入
		ReferenceRatio          string                    `json:"referenceratio" bson:"referenceratio"`                   //参考倍率
		TargetRatio             string                    `json:"targetratio" bson:"targetratio"`                         //目标倍率
		FactoryPrice            string                    `json:"factoryprice" bson:"factoryprice"`                       //工厂吊牌价
		TargetPrice             string                    `json:"targetprice" bson:"targetprice"`                         //下单成本
		OrderQuantity           string                    `json:"orderquantity" bson:"orderquantity"`                     //品牌预定数量
		OrderPrice              string                    `json:"orderprice" bson:"orderprice"`                           //品牌预订预售价 (11/1 add)
		ProductProperty         string                    `json:"productproperty" bson:"productproperty"`                 //产品属性
		Meeting                 int                       `json:"meeting" bson:"meeting"`                                 //是否过会i
		OrderInfo               []Order                   `json:"orderinfo" bson:"orderinfo"`                             //预订
		UploadWaterReport       []string                  `json:"uploadwaterreport" bson:"uploadwaterreport"`             // 水洗报告
		NewDay                  time.Time                 `json:"newday" bson:"newday"`                                   // 过会组更新 上新日
		OrderStatus             int                       `json:"orderstatus" bson:"orderstatus"`                         //是否下单
		OrderCount              int                       `json:"ordercount" bson:"ordercount"`                           // 下单数量
		Count                   int                       `json:"count" bson:"count"`                                     // 入库数量
		InboundDate             time.Time                 `json:"inbounddate" bson:"inbounddate"`                         // 最近入库日期
		MeetingStatus           int                       `json:"meetingstatus" bson:"meetingstatus"`                     //过会状态
		NewStatus               int                       `json:"newstatus" bson:"newstatus"`                             //上新状态
		OnlineTime              time.Time                 `json:"onlinetime" bson:"onlinetime"`                           // 线上提交检测时间
		OnlineStatus            int                       `json:"onlinestatus" bson:"onlinestatus"`                       //线上提交检测状态
		PhotoStatus             int                       `json:"photostatus" bson:"photostatus"`                         //是否安排拍照
		CertPic                 []string                  `json:"certpic" bson:"certpic"`                                 // 合格证报告
		WashPic                 []string                  `json:"washpic" bson:"washpic"`                                 // 水洗唛照片
		SizeSpecificationsTable []string                  `json:"sizespecificationstable" bson:"sizespecificationstable"` // 尺码推荐表
		SizeRecommendationTable []string                  `json:"sizerecommendationtable" bson:"sizerecommendationtable"` // 尺寸规格表
		Pattern                 []string                  `json:"pattern" bson:"pattern"`                                 // 版师组 纸样
		Picture                 []string                  `json:"picture" bson:"picture"`                                 // 图片
		PropertyStatus          int                       `json:"propertystatus" bson:"propertystatus"`                   //生产组产品属性编辑状态
		UploadTestReport        []string                  `json:"uploadtestreport" bson:"uploadtestreport"`               // 上传检测报告
		TestReportTime          time.Time                 `json:"testreporttime" bson:"testreporttime"`                   // 检测报告完成时间
		DesignPropertyStatus    int                       `json:"designpropertystatus" bson:"designpropertystatus"`       //设计组产品属性状态
		DesignEditerStatus      int                       `json:"designediterstatus" bson:"designediterstatus"`           //设计组版师状态
		ProductPropertyStatus   int                       `json:"productpropertystatus" bson:"productpropertystatus"`     //设计组产品属性状态
		PicResTime              time.Time                 `json:"picrestime" bson:"picrestime"`                           // 摄影组出图日期
		PhotoTime               time.Time                 `json:"phototime" bson:"phototime"`                             // 摄影组拍照日期
		PhotoTransferTime       time.Time                 `json:"phototransfertime" bson:"phototransfertime"`             // 拍照样转交日期
		EditerCompleteTime      time.Time                 `json:"editercompletetime" bson:"editercompletetime"`           // 尺码推荐完成时间
		SkuColor                []string                  `json:"skucolor" bson:"skucolor"`                               //sku颜色
		PhotographyStatus       int                       `json:"photographystatus" bson:"photographystatus"`             //sku颜色
		FaceTime                time.Time                 `json:"facetime" bson:"facetime"`                               //sku颜色
		FaceStatus              int                       `json:"facestatus" bson:"facestatus"`                           //sku颜色
		Note                    string                    `json:"note" bson:"note"`                                       // 备注
		FollowUser              string                    `json:"followuser" bson:"followuser"`                           // 跟单员 11.1
		Tabs                    string                    `json:"tabs" bson:"tabs"`                                       // 物料单
		Qualityreport           []string                  `json:"qualitytestreport" bson:"qualitytestreport"`             // 质检结果 11.4
		Packagecost             []productproperty.Compose `json:"packagecost" bson:"packagecost"`                         // 包装成本 11.4
		Processcost             []productproperty.Compose `json:"processcost" bson:"processcost"`                         // 加工成本 11.4
		PackagecostTotal        float64                   `json:"packagecosttotal" bson:"packagecosttotal"`               // 包装成本合计 11.4
		ProcesscostTotal        float64                   `json:"processcosttotal" bson:"processcosttotal"`               // 加工成本合计 11.4
		ProductNote             string                    `json:"productnote" bson:"productnote"`                         // 跟单员 11.1
		ProductSatus            string                    `json:"productstatus" bson:"productstatus"`                     // 物料单
		WhetherImportErpInfo    string                    `json:"whetherimporterpinfo" bson:"whetherimporterpinfo"`       // erp 信息是否同步
	}
	insertproductplan struct {
		DesignPlanID            string                    `json:"designplanid" bson:"designplanid"`                       //大货号
		Number                  string                    `json:"number" bson:"number"`                                   //流水号
		LargeCargoNumber        string                    `json:"largecargonumber" bson:"largecargonumber"`               //大货号
		Brand                   string                    `json:"brand" bson:"brand"`                                     //品牌
		DesignNumber            string                    `json:"designnumber" bson:"designnumber"`                       //设计号
		ModelName               string                    `json:"modelname" bson:"modelname"`                             //款名
		FactoryNumber           string                    `json:"factorynumber" bson:"factorynumber"`                     //工厂款号
		Gender                  string                    `json:"gender" bson:"gender"`                                   //性别
		ProductCategory         string                    `json:"productcategory" bson:"productcategory"`                 //产品大类
		ProductKind             string                    `json:"productkind" bson:"productkind"`                         //品类
		Color                   []string                  `json:"color" bson:"color"`                                     //颜色
		DesignPic               []string                  `json:"designpic" bson:"designpic"`                             //设计稿
		Designer                string                    `json:"designer" bson:"designer"`                               //设计师
		Batch                   string                    `json:"batch" bson:"batch"`                                     //批次
		Provider                string                    `json:"provider" bson:"provider"`                               //供应商
		FactoryCost             string                    `json:"factorycost" bson:"factorycost"`                         //工厂报价
		TargetCost              string                    `json:"targetcost" bson:"targetcost"`                           //目标成本
		FinallyCost             string                    `json:"finallycost" bson:"finallycost"`                         //最终成本
		ReferenceRatio          string                    `json:"referenceratio" bson:"referenceratio"`                   //参考倍率
		TargetRatio             string                    `json:"targetratio" bson:"targetratio"`                         //工厂吊牌价
		FactoryPrice            string                    `json:"factoryprice" bson:"factoryprice"`                       //工厂吊牌价
		TargetPrice             string                    `json:"targetprice" bson:"targetprice"`                         //下单成本
		OrderQuantity           string                    `json:"orderquantity" bson:"orderquantity"`                     //品牌预定数量
		OrderPrice              string                    `json:"orderprice" bson:"orderprice"`                           //品牌预订预售价 (11/1 add)
		ProductProperty         string                    `json:"productproperty" bson:"productproperty"`                 //产品属性
		Meeting                 int                       `json:"meeting" bson:"meeting"`                                 //是否过会i
		OrderStatus             int                       `json:"orderstatus" bson:"orderstatus"`                         //是否下单
		OrderInfo               []Order                   `json:"orderinfo" bson:"orderinfo"`                             //预订
		UploadWaterReport       []string                  `json:"uploadwaterreport" bson:"uploadwaterreport"`             // 水洗报告
		NewDay                  time.Time                 `json:"newday" bson:"newday"`                                   // 过会组更新 上新日
		OrderCount              int                       `json:"ordercount" bson:"ordercount"`                           // 下单数量
		Count                   int                       `json:"count" bson:"count"`                                     // 入库数量
		InboundDate             time.Time                 `json:"inbounddate" bson:"inbounddate"`                         // 最近入库日期
		MeetingStatus           int                       `json:"meetingstatus" bson:"meetingstatus"`                     //过会状态
		NewStatus               int                       `json:"newstatus" bson:"newstatus"`                             //上新状态
		OnlineTime              time.Time                 `json:"onlinetime" bson:"onlinetime"`                           // 线上提交检测时间
		OnlineStatus            int                       `json:"onlinestatus" bson:"onlinestatus"`                       //线上提交检测状态
		PhotoStatus             int                       `json:"photostatus" bson:"photostatus"`                         //是否安排拍照
		CertPic                 []string                  `json:"certpic" bson:"certpic"`                                 // 合格证报告
		WashPic                 []string                  `json:"washpic" bson:"washpic"`                                 // 水洗唛照片
		SizeSpecificationsTable []string                  `json:"sizespecificationstable" bson:"sizespecificationstable"` // 尺寸规格表
		SizeRecommendationTable []string                  `json:"sizerecommendationtable" bson:"sizerecommendationtable"` // 尺码推荐规格表
		Pattern                 []string                  `json:"pattern" bson:"pattern"`                                 // 版师组 纸样
		Picture                 []string                  `json:"picture" bson:"picture"`                                 // 图片
		PropertyStatus          int                       `json:"propertystatus" bson:"propertystatus"`                   //生产组产品属性编辑状态
		UploadTestReport        []string                  `json:"uploadtestreport" bson:"uploadtestreport"`               // 上传检测报告
		TestReportTime          time.Time                 `json:"testreporttime" bson:"testreporttime"`                   // 检测报告完成时间
		DesignPropertyStatus    int                       `json:"designpropertystatus" bson:"designpropertystatus"`       //设计组产品属性状态
		DesignEditerStatus      int                       `json:"designediterstatus" bson:"designediterstatus"`           //设计组版师状态
		ProductPropertyStatus   int                       `json:"productpropertystatus" bson:"productpropertystatus"`     //设计组产品属性状态
		PicResTime              time.Time                 `json:"picrestime" bson:"picrestime"`                           // 摄影组出图日期
		PhotoTime               time.Time                 `json:"phototime" bson:"phototime"`                             // 摄影组拍照日期
		PhotoTransferTime       time.Time                 `json:"phototransfertime" bson:"phototransfertime"`             // 拍照样转交日期
		EditerCompleteTime      time.Time                 `json:"editercompletetime" bson:"editercompletetime"`           // 尺码推荐完成时间
		SkuColor                []string                  `json:"skucolor" bson:"skucolor"`                               //sku颜色
		PhotographyStatus       int                       `json:"photographystatus" bson:"photographystatus"`             //摄影组状态
		FaceTime                time.Time                 `json:"facetime" bson:"facetime"`                               //平面完成时间
		FaceStatus              int                       `json:"facestatus" bson:"facestatus"`                           //平面组状态
		Note                    string                    `json:"note" bson:"note"`                                       // 备注
		FollowUser              string                    `json:"followuser" bson:"followuser"`                           // 跟单员 11.1
		Tabs                    string                    `json:"tabs" bson:"tabs"`                                       // 物料单
		Qualityreport           []string                  `json:"qualitytestreport" bson:"qualitytestreport"`             // 质检结果 11.4
		Packagecost             []productproperty.Compose `json:"packagecost" bson:"packagecost"`                         // 包装成本 11.4
		Processcost             []productproperty.Compose `json:"processcost" bson:"processcost"`                         // 加工成本 11.4
		PackagecostTotal        float64                   `json:"packagecosttotal" bson:"packagecosttotal"`               // 包装成本合计 11.4
		ProcesscostTotal        float64                   `json:"processcosttotal" bson:"processcosttotal"`               // 加工成本合计 11.4
		ProductNote             string                    `json:"productnote" bson:"productnote"`                         // 跟单员 11.1
		ProductSatus            string                    `json:"productstatus" bson:"productstatus"`                     // 物料单
		WhetherImportErpInfo    string                    `json:"whetherimporterpinfo" bson:"whetherimporterpinfo"`       // erp 信息是否同步
	}
	skuorder struct {
		ID                     bson.ObjectId `json:"_id" bson:"_id"`
		ProductID              string        `json:"productid" bson:"productid"`
		ProductctionGroupID    string        `json:"productctiongroupid" bson:"productctiongroupid"`
		SkuCode                string        `json:"skucode" bson:"skucode"`
		SkuDesc                string        `json:"skudesc" bson:"skudesc"`
		ClothingSupplier       string        `json:"clothingsupplier" bson:"clothingsupplier"`
		WatermarkNumber        string        `json:"watermarknumber" bson:"watermarknumber"`
		WatermarkSupplier      string        `json:"watermarksupplier" bson:"watermarksupplier"`
		WatermarkSingleMoney   string        `json:"watermarksinglemoney" bson:"watermarksinglemoney"`
		CertificateNumber      string        `json:"certificatenumber" bson:"certificatenumber"`
		CertificateSupplier    string        `json:"certificatesupplier" bson:"certificatesupplier"`
		CertificateSingleMoney string        `json:"certificatesinglemoney" bson:"certificatesinglemoney"`
		SizemarkNumber         string        `json:"sizemarknumber" bson:"sizemarknumber"`
		SizemarkSupplier       string        `json:"sizemarksupplier" bson:"sizemarksupplier"`
		SizemarkSingleMoney    string        `json:"sizemarksinglemoney" bson:"sizemarksinglemoney"`
		Count                  string        `json:"count" bson:"count"`
		OrderCount             string        `json:"ordercount" bson:"ordercount"`
		Cost                   string        `json:"cost" bson:"cost"`
		OrderTime              string        `json:"ordertime" bson:"ordertime"`
		Time                   string        `json:"time" bson:"time"`
		SkuList                string        `json:"skulist" bson:"skulist"`
		Fabriccost             string        `json:"fabriccost" bson:"fabriccost"`
		Fabrictotal            string        `json:"fabrictotal" bson:"fabrictotal"`
		Feathercost            string        `json:"feathercost" bson:"feathercost"`
		Feathertotal           string        `json:"feathertotal" bson:"feathertotal"`
		Fabricsupplier         string        `json:"fabricsupplier" bson:"fabricsupplier"`
		Feathersupplier        string        `json:"feathersupplier" bson:"feathersupplier"`
		Factorymodelnumber     string        `json:"factorymodelnumber" bson:"factorymodelnumber"`
		IsEdiet                bool          `json:"isedit" bson:"isedit"`
		ContractStatus         string        `json:"contractstatus" bson:"contractstatus"`
		Contract               string        `json:"contract" bson:"contract"`
	}
	Order struct {
		Brand  string `json:"brand" bson:"brand"`   //品牌
		Number string `json:"number" bson:"number"` //流水号
		Count  string `json:"count" bson:"count"`   //数量
	}
	LargeNumber struct {
		Skudesc string `json:"skudesc" bson:"skudesc"` //品牌
	}

	UpdateLargeNumber struct {
		OldLargeCargoNumber string `json:"oldlargecargonumber" bson:"oldlargecargonumber"` //大货号
		NewLargeCargoNumber string `json:"newlargecargonumber" bson:"newlargecargonumber"` //大货号

	}
)

type OXYProductPlanData struct{}

func NewOXYProductPlanData() *OXYProductPlanData {
	designPlanData := &OXYProductPlanData{}
	return designPlanData
}

func (opd *OXYProductPlanData) GetProductPlanListHandler(c echo.Context) error {
	log.Info("GetProductPlanListHandler")
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, count, err := model.DB().QuerySort(M, currentpage, perpage, "-_id")
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []Productplan{}
	query.All(&ps)
	str, err := json.Marshal(ps)
	query = nil
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  string(str),
		"count": count,
	})
	return nil
}

func (opd *OXYProductPlanData) GetProductPlanInfoHandler(c echo.Context) error {
	log.Info("GetProductPlanInfoHandler")
	id := c.QueryParam("id")
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan"
	query, err := model.DB().QueryOne(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	p := Productplan{}
	query.One(&p)
	if err != nil {
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"data": p,
	})

	return nil
}

func (opd *OXYProductPlanData) AddProductPlanHandler(c echo.Context) error {

	log.Info("AddProductPlanHandler")
	list := &[]insertproductplan{}
	if err := c.Bind(list); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}

	var docs []interface{}
	for _, v := range *list {
		docs = append(docs, v)
	}

	var count = 0
	largeNumberList := []string{}
	for _, item := range *list {
		model.DB().Dbname = "OxyCms"
		model.DB().Document = "product_plan"
		err := model.DB().Insert(item)
		if err != nil {
			count++
			largeNumberList = append(largeNumberList, item.LargeCargoNumber)
			model.DB().Update(bson.M{"largecargonumber": item.LargeCargoNumber}, bson.M{"$set": bson.M{"orderquantity": item.OrderQuantity, "orderprice": item.OrderPrice, "note": item.Note}})
			log.Error("插入出错", err)
			continue
		}

		model.DB().Dbname = "OxyDic"
		model.DB().Document = "serialNumber"
		selector := bson.M{"brand": item.Brand, "number": item.Number}
		data := bson.M{"$set": bson.M{"flag": "1"}}
		err = model.DB().Update(selector, data)
		if err != nil {
			log.Error("更新流水号表出错", err)
		}
	}
	if count > 0 {
		c.JSON(200, map[string]interface{}{
			"msg":  "error",
			"info": largeNumberList,
		})

		return nil
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
func (opd *OXYProductPlanData) UpdateProductPlanHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("UpdateProductPlanHandler", id)

	o := &insertproductplan{}

	if err := c.Bind(o); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan"

	query, err := model.DB().QueryOne(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	p := Productplan{}
	query.One(&p)
	s, err := json.Marshal(p)
	bufbody := bytes.NewBuffer(s)
	c.Request().Body = ioutil.NopCloser(bufbody)

	o.Count = p.Count             // 入库数量
	o.OrderCount = p.OrderCount   // 下单数量
	o.OrderStatus = p.OrderStatus // 下单状态
	o.InboundDate = p.InboundDate
	err = model.DB().Update(bson.M{"_id": bson.ObjectIdHex(id)}, o)
	if err != nil {
		log.Error("更新出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
func (opd *OXYProductPlanData) DelProductPlanHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DelProductPlanHandler", id)
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan"
	query, err := model.DB().QueryOne(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	p := Productplan{}
	query.One(&p)
	s, err := json.Marshal(p)
	bufbody := bytes.NewBuffer(s)
	c.Request().Body = ioutil.NopCloser(bufbody)

	err = model.DB().Remove(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		log.Error("删除出错 product_plan", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	// 更新设计组预订单,查询设计组数据
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_plan"
	queryDes, err := model.DB().QueryOne(bson.M{"_id": bson.ObjectIdHex(p.DesignPlanID)})
	if err != nil {
		log.Error("删除生产组,查询设计组数据失败")
	}
	designData := designplan.Designplan{}
	designOrder := []designplan.Order{}
	queryDes.One(&designData)
	for _, des := range designData.Order {
		if des.LargeNumber != p.LargeCargoNumber {
			designOrder = append(designOrder, des)
		}
	}
	// 更新设计组预订单,更新设计组预订单数据
	selector := bson.M{"_id": bson.ObjectIdHex(p.DesignPlanID)}
	data := bson.M{"$set": bson.M{"order": designOrder}}
	err = model.DB().Update(selector, data)
	if err != nil {
		log.Error("删除生产组时 更新设计组预订单出错,", err)
	}

	// 删除订单
	model.DB().Document = "sku_order"
	err = model.DB().Remove(bson.M{"productid": id})
	if err != nil {
		log.Error("删除出错 订单 sku_order", err)
	}
	// 删除sku
	model.DB().Document = "sku"
	err = model.DB().Remove(bson.M{"productid": id})
	if err != nil {
		log.Error("删除出错 sku", err)
	}

	// 回收流水号
	model.DB().Dbname = "OxyDic"
	model.DB().Document = "serialNumber"
	err = model.DB().Update(bson.M{"brand": p.Brand, "number": p.Number}, bson.M{"$set": bson.M{"flag": "0"}})
	if err != nil {
		log.Error("回收流水号失败", err)
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})
	return nil
}

func (opd *OXYProductPlanData) DelProductPlanListHandler(c echo.Context) error {
	jsonquery := c.QueryParam("like")
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan"
	log.Info("like", jsonquery)
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, _, err := model.DB().Query(M, 0, 0)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []Productplan{}
	query.All(&ps)
	for _, item := range ps {
		model.DB().Dbname = "OxyCms"
		model.DB().Document = "product_plan"
		err := model.DB().Remove(bson.M{"_id": item.ID})
		if err != nil {
			log.Error("删除出错 product_plan", err)
			c.JSON(404, map[string]interface{}{
				"msg": "error",
			})
			return err
		}

		// 删除订单
		model.DB().Document = "sku_order"
		err = model.DB().Remove(bson.M{"productid": item.ID.Hex()})
		if err != nil {
			log.Error("删除出错 订单sku_order", err)
		}
		// 删除sku
		model.DB().Document = "sku"
		_, err = model.DB().RemoveAll(bson.M{"productid": item.ID.Hex()})
		if err != nil {
			log.Error("删除出错 sku", err)
		}

		// 回收流水号
		model.DB().Dbname = "OxyDic"
		model.DB().Document = "serialNumber"
		err = model.DB().Update(bson.M{"brand": item.Brand, "number": item.Number}, bson.M{"$set": bson.M{"flag": "0"}})
		if err != nil {
			log.Error("回收流水号失败", err)
		}
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})
	return nil
}

// 更新生产组大货号 和订单大货号
func (opd *OXYProductPlanData) UpdateProductLargeNumber(c echo.Context) error {
	log.Info("UpdateProductLargeNumber")
	o := []UpdateLargeNumber{}
	if err := c.Bind(&o); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	for _, v := range o {
		model.DB().Document = "product_plan"
		err := model.DB().Update(bson.M{"largecargonumber": v.OldLargeCargoNumber}, bson.M{"$set": bson.M{"largecargonumber": v.NewLargeCargoNumber}})
		if err != nil {
			log.Error("更新生产组大货号出错:", v.OldLargeCargoNumber, err)
		}

		model.DB().Document = "sku_order"
		err = model.DB().Update(bson.M{"skudesc": v.OldLargeCargoNumber}, bson.M{"$set": bson.M{"skudesc": v.NewLargeCargoNumber}})
		if err != nil {
			log.Error("更新订单大货号出错:", v.OldLargeCargoNumber, err)
		}
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})
	return nil
}

// 更新设计组大货号
func (opd *OXYProductPlanData) UpdateDesignPlanListOrderInfoHandler(c echo.Context) error {
	log.Info("UpdateDesignPlanListOrderInfoHandler")
	data := []UpdateLargeNumber{}
	if err := c.Bind(&data); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_plan"

	query, _, err := model.DB().Query(nil, 0, 0)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []designplan.Designplan{}
	query.All(&ps)
	LargeCargoNumberMap := make(map[string]string)
	for _, d := range data {
		LargeCargoNumberMap[d.OldLargeCargoNumber] = d.NewLargeCargoNumber
	}
	log.Info("LargeCargoNumberMap", LargeCargoNumberMap)
	for _, des := range ps {
		flag := false
		if len(des.Order) > 0 {
			for i, o := range des.Order {
				if largenumber, ok := LargeCargoNumberMap[o.LargeNumber]; ok {
					flag = true
					des.Order[i].LargeNumber = largenumber
				}
			}
		}
		if flag {
			model.DB().Document = "design_plan"
			err := model.DB().Update(bson.M{"_id": bson.ObjectId(des.ID)}, bson.M{"$set": bson.M{"order": des.Order}})
			if err != nil {
			}
		}
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
